const svc = require('../util/service')
const logger = require('log4js').getLogger()
const config = require('../util/config')

module.exports = (req, res) => {
    svc.handlePost(req, res, (reqObj, resolve) => {
        const mongoMng = require('../mng/mongoMng')
        if (!mongoMng.db) {
            logger.error('[' + __filename + ':' + __line + ']', '未连接mongo')
            resolve({
                result: -1,
                msg: '系统错误'
            })
            return
        }
        var promise0 = new Promise(resolve => {
            mongoMng.db.collection('user').find({
                isPromoter: true
            }).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve([])
                    return
                }
                var promoters = []
                result.forEach(item => {
                    promoters.push({
                        phone: item.phone,
                        name: item.name || '',
                        customers: [],
                        returnPromoterMoney: 0,
                        willReturnPromoterMoney: 0
                    })
                })
                resolve(promoters)
            })
        }),
        promise1 = new Promise(resolve => {
            mongoMng.db.collection('user').aggregate([{
                $match: {
                    promoter: {
                        $ne: null
                    }
                }
            }, {
                $group: {
                    _id: '$promoter',
                    customers: {
                        $addToSet: '$phone'
                    }
                }
            }]).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve([])
                    return
                }
                resolve(result)
            })
        }),
        promise2 = new Promise(resolve => {
            mongoMng.db.collection('bill').aggregate([{
                $match: {
                    returnPromoterMoney: {
                        $ne: null
                    }
                }
            }, {
                $group: {
                    _id: '$customer_phone',
                    returnPromoterMoney: {
                        $sum: '$returnPromoterMoney'
                    }
                }
            }]).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve([])
                    return
                }
                resolve(result)
            })
        }),
        promise3 = new Promise(resolve => {
            mongoMng.db.collection('bill').aggregate([{
                $match: {
                    returnPromoterTime: null,
                    returnTime: {
                        $ne: null
                    }
                }
            }, {
                $group: {
                    _id: '$customer_phone',
                    returnMoney: {
                        $sum: '$returnMoney'
                    }
                }
            }]).toArray((err, result) => {
                if (err) {
                    logger.error('[' + __filename + ':' + __line + ']', err)
                    resolve([])
                    return
                }
                resolve(result)
            })
        })
        Promise.all([promise0, promise1, promise2, promise3]).then(result => {
            var promoters = result[0]

            promoters.forEach(item => {
                for (var i = 0; i < result[1].length; ++i) {
                    if (result[1][i]._id == item.phone) {
                        item.customers = result[1][i].customers
                        break
                    }
                }
            })

            promoters.forEach(item => {
                item.customers.forEach(_item => {
                    for (var i = 0; i < result[2].length; ++i) {
                        if (result[2][i]._id == _item) {
                            item.returnPromoterMoney += result[2][i].returnPromoterMoney
                            break
                        }
                    }
                })
                item.returnPromoterMoney = Math.round(item.returnPromoterMoney * 100) / 100
            })

            promoters.forEach(item => {
                item.customers.forEach(_item => {
                    for (var i = 0; i < result[3].length; ++i) {
                        if (result[3][i]._id == _item) {
                            item.willReturnPromoterMoney += result[3][i].returnMoney / config.returnRate * config.returnPromoterRate
                            break
                        }
                    }
                })
                item.willReturnPromoterMoney = Math.round(item.willReturnPromoterMoney * 100) / 100
            })

            resolve(promoters)
        })
    })
}
